package com.notary.util;

import cn.hutool.core.util.RandomUtil;
import com.itextpdf.text.pdf.PdfReader;
import com.notary.entity.vo.JsonResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;

public class PdfToImg {

    /**
     * 生成html模板文件
     *
     * @param tempFilePath 模板文件位置
     * @param content      模板内容
     * @param paramMap     模板填充数据
     * @return
     */
    public static JsonResult createdHtmlTemplate(String content, Map<String, Object> paramMap, String tempFilePath) {
        try {
            for (String key : paramMap.keySet()) {
                content = content.replaceAll("\\{\\{=" + key + "}}", paramMap.get(key).toString());
            }
//            Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
//            configuration.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_23));
//            configuration.setDefaultEncoding("UTF-8");   //这个一定要设置，不然在生成的页面中 会乱码
//            //获取或创建一个模版
//            Template template = new Template("template", new StringReader(content), configuration);
//            StringWriter stringWriter = new StringWriter();
//            BufferedWriter writer = new BufferedWriter(stringWriter);
//            template.process(paramMap, writer); //把值写进模板
//            writer.flush();
//            writer.close();
            File tempFile = new File(tempFilePath);
            if (!tempFile.isFile())
                tempFile.createNewFile();
            PrintStream printStream = new PrintStream(new FileOutputStream(tempFile));
            printStream.println(content);
            printStream.flush();
            printStream.close();
            return JsonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.fail();
        }
    }

    /**
     * 生成html模板string
     *
     * @param content  模板内容
     * @param paramMap 模板填充数据
     * @return
     */
    public static JsonResult createdHtmlTemplate(String content, Map<String, Object> paramMap) {
        try {
//            Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
//            configuration.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_23));
//            configuration.setDefaultEncoding("UTF-8");   //这个一定要设置，不然在生成的页面中 会乱码
//            //获取或创建一个模版
//            Template template = new Template("template", new StringReader(content), configuration);
//            StringWriter stringWriter = new StringWriter();
//            BufferedWriter writer = new BufferedWriter(stringWriter);
//            template.process(paramMap, writer); //把值写进模板
//            writer.flush();
//            writer.close();
            if (paramMap != null) {
                for (String key : paramMap.keySet()) {
                    content = content.replaceAll("\\{\\{=" + key + "}}", paramMap.get(key).toString());
                }
            }
            return JsonResult.success(content);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.fail();
        }
    }

    /***
     * PDF文件转PNG图片，全部页数
     *
     * @param PdfFilePath pdf完整路径
     * @param dstImgFolder 图片存放的文件夹
     * @param dpi dpi越大转换后越清晰，相对转换速度越慢
     * @return
     */

    public static List<String> pdf2Image(String PdfFilePath, String dstImgFolder, int dpi) {
        File file = new File(PdfFilePath);
        PDDocument pdDocument;
        List<String> lst = null;
        try {
            String imgPDFPath = file.getParent();
            String imgFolderPath = StringUtils.isEmpty(dstImgFolder) ? imgPDFPath : dstImgFolder;

            int dot = file.getName().lastIndexOf('.');
            String imagePDFName = file.getName().substring(0, dot); // 获取图片文件名
//            if (dstImgFolder.equals("")) {
////                imgFolderPath = imgPDFPath + File.separator + imagePDFName;// 获取图片存放的文件夹路径
//                imgFolderPath = imgPDFPath ;// 获取图片存放的文件夹路径
//            } else {
////                imgFolderPath = dstImgFolder + File.separator + imagePDFName;
//                imgFolderPath = dstImgFolder;
//            }

            if (createDirectory(imgFolderPath)) {
                pdDocument = PDDocument.load(file);
                lst = new ArrayList();
                PDFRenderer renderer = new PDFRenderer(pdDocument);
                /* dpi越大转换后越清晰，相对转换速度越慢 */
                PdfReader reader = new PdfReader(PdfFilePath);
                int pages = reader.getNumberOfPages();
                StringBuffer imgFilePath = null;
                for (int i = 0; i < pages; i++) {
                    String imgFilePathPrefix = imgFolderPath + File.separator + imagePDFName;
                    imgFilePath = new StringBuffer();
                    imgFilePath.append(imgFilePathPrefix);
                    imgFilePath.append("_");
                    imgFilePath.append(String.valueOf(i + 1));
                    imgFilePath.append("_");

                    imgFilePath.append(RandomUtil.randomNumbers(8));
                    imgFilePath.append(".png");
                    File dstFile = new File(imgFilePath.toString());
                    BufferedImage image = renderer.renderImageWithDPI(i, dpi);
                    ImageIO.write(image, "png", dstFile);
                    lst.add(imgFilePath.toString());
                }
//                System.out.println("PDF文档转PNG图片成功！");
            } else {
//                System.out.println("PDF文档转PNG图片失败：" + "创建" + imgFolderPath + "失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return lst;
    }


    private static boolean createDirectory(String folder) {
        File dir = new File(folder);
        if (dir.exists()) {
            return true;
        } else {
            return dir.mkdirs();
        }
    }

    public static void main(String[] args) {
        System.out.println(pdf2Image("E:\\test789.pdf", "e:\\img\\z.png", 100));
    }
}
